/*
 * Copyright 2010 Christian Matzat and others
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package net.matzat.android.hiberdroid;

import net.matzat.android.hiberdroid.annotation.Column;
import net.matzat.android.hiberdroid.annotation.Entity;
import net.matzat.android.hiberdroid.annotation.Id;
import net.matzat.android.hiberdroid.annotation.Transient;
import net.matzat.android.hiberdroid.exception.DuplicateMappingException;
import net.matzat.android.hiberdroid.exception.MappingNotFoundException;
import net.matzat.android.hiberdroid.mapping.EntityMapping;
import org.apache.commons.lang.ModStringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Configuration {

    private static List<EntityMapping> entities;
    private static final String TAG = "hiberdroid." + Configuration.class.getSimpleName();

    //Control instantiation. Only one Instance allowed.
    private Configuration(String... typeClasses) throws ClassNotFoundException, InstantiationException {
        if (entities != null) {
            throw new InstantiationException("Instance of Configuration was already created.");
        }
        try {
            entities = new ArrayList<EntityMapping>();
            for (String typeClass : typeClasses) {
                entities.add(initClass(Class.forName(typeClass)));
            }
        } catch (ClassNotFoundException e) {
            entities = null;
            throw new ClassNotFoundException(e.getMessage());
        }
    }

    /**
     * Creates an instance of Configuration. Only one instance of Configuration ist allowed.
     *
     * @param typeClasses the POJO classes that contains the property what should be mapped to the database
     * @return a new instance of Configuration
     * @throws ClassNotFoundException one of the typeClasses was not found at runtime
     * @throws InstantiationException an instance of Configuration was already created
     */
    static Configuration createInstance(String... typeClasses) throws ClassNotFoundException, InstantiationException {
        return new Configuration(typeClasses);
    }

    // creates the mapping for each class
    private EntityMapping initClass(Class typeClass) {
        EntityMapping entity = new EntityMapping(typeClass);
        Annotation[] annotations = typeClass.getAnnotations();
        String annotationConfiguredTable = null;
        for (Annotation annotation : annotations) {
            if (annotation instanceof Entity) {
                Entity entityAnnotation = (Entity) annotation;
                annotationConfiguredTable = ModStringUtils.isNotBlank(entityAnnotation.table()) ? entityAnnotation.table() : null;
            }
        }
        entity.setTable(annotationConfiguredTable == null ? typeClass.getSimpleName().toLowerCase() : annotationConfiguredTable);
        for (Method method : typeClass.getDeclaredMethods()) {
            getMethodAnnotations(entity, method);
        }
        for (Field field : typeClass.getDeclaredFields()) {
            getFieldAnnotations(entity, field);
        }
        return entity;
    }

    // process Annotations on methods
    private Annotation[] getMethodAnnotations(EntityMapping entity, Method method) {
        Annotation[] annotations = method.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof Column) {
                Column columnAnnotiation = (Column) annotation;
                addColumn(annotation, method, entity, columnAnnotiation.name());
            } else if (annotation instanceof Id) {
                Id idAnnotiation = (Id) annotation;
                if (entity.getIdProperty() != null) {
                    throw new DuplicateMappingException("more than one id property configured.");
                }
                addColumn(annotation, method, entity, idAnnotiation.name());
            }
        }
        return annotations;
    }

    // process Annotations on fields (properties)
    private Annotation[] getFieldAnnotations(EntityMapping entity, Field field) {
        Annotation[] annotations = field.getAnnotations();
        if (annotations.length > 0) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof Transient) {
                    // ommit this field
                } else if (annotation instanceof Id) {
                    Id idAnnotiation = (Id) annotation;
                    if (entity.getIdProperty() != null) {
                        throw new DuplicateMappingException("more than one id property configured.");
                    }
                    entity.addColumn(annotation, field.getType(), ModStringUtils.isNotBlank(idAnnotiation.name()) ? idAnnotiation.name() : field.getName().toLowerCase(), field.getName());
                } else if (annotation instanceof Column) {
                    Column columnAnnotiation = (Column) annotation;
                    entity.addColumn(annotation, field.getType(), ModStringUtils.isNotBlank(columnAnnotiation.name()) ? columnAnnotiation.name() : field.getName().toLowerCase(), field.getName());
                } else {
                    if (!entity.getColumns().containsKey(field.getName())) {
                        entity.addColumn(annotation, field.getType(), field.getName().toLowerCase(), field.getName());
                    }
                }
            }
        } else {
            if (!entity.getColumns().containsKey(field.getName())) {
                entity.addColumn(null, field.getType(), field.getName().toLowerCase(), field.getName());
            }
        }
        return annotations;
    }

    // add a resolved column to the mapping
    private void addColumn(Annotation annotation, Method method, EntityMapping entity, String annotatedColumnName) {
        Class type = method.getName().startsWith("set") ? method.getParameterTypes()[0] : method.getReturnType();
        String property = stripGetSet(method.getName());
        String column = ModStringUtils.isNotBlank(annotatedColumnName) ? annotatedColumnName : property.toLowerCase();
        entity.addColumn(annotation, type, column, property);
    }

    // strip get/set/has/is from JavaBeans conform methods
    private String stripGetSet(String name) {
        String property = name;
        if (name.startsWith("set") || name.startsWith("get") || name.startsWith("has")) {
            property = name.substring(3);
        } else if (name.startsWith("is")) {
            property = name.substring(2);
        }
        return ModStringUtils.uncapitalize(property);
    }

    /**
     * Get a List of the configured entitie mappings.
     *
     * @return a List of configured entities
     */
    public static List<EntityMapping> getEntities() {
        return entities;
    }

    /**
     * Resolves an entity mapping for a specific class.
     *
     * @param entityClass the class to search for
     * @return the specific entity mapping for this class
     */
    public static EntityMapping findEntityMappingByClass(Class entityClass) {
        for (EntityMapping mapping : Configuration.getEntities()) {
            if (mapping.getEntityClass().equals(entityClass)) {
                return mapping;
            }
        }
        throw new MappingNotFoundException("mapping for class " + entityClass.getName() + " not found.");
    }

    /**
     * Destroys the current instance
     */
    public static void destroy() {
        entities = null;
    }
}

